import { Navigate } from "react-router-dom";
import { lazy } from "react";
import { useLocation } from "react-router-dom";
import Login from "../pages/login";
import MainLayout from "../layouts/Layout";

// 懒加载组件
const Home = lazy(() => import("../pages/home"));
const UserManager = lazy(() => import("../pages/userManager"));
const RoleManager = lazy(() => import("../pages/roleManager"));
const MenuManager = lazy(() => import("../pages/menuManager"));
const OperationLog = lazy(() => import("../pages/operationLog"));
const Common = lazy(() => import("../pages/common"));

// 动态路由组件，用来判断是否应该显示 Common 组件
const DynamicRoute = () => {
  const location = useLocation();

  // 如果路径包含 "common"，渲染 Common 组件
  if (location.pathname.includes("common")) {
    return <Common />;
  }

  // 否则重定向到首页
  return <Navigate to="/home" replace />;
};

// 基础路由配置
export const baseRoutes = [
  {
    path: "/",
    element: <MainLayout />,
    children: [
      {
        path: "/",
        element: <Navigate to="/home" replace />,
      },
      {
        path: "/home",
        element: <Home />,
        handle: { title: "首页" },
      },
      {
        path: "/userManager",
        element: <UserManager />,
        handle: { title: "用户设置" },
      },
      {
        path: "/roleManager",
        element: <RoleManager />,
        handle: { title: "角色设置" },
      },
      {
        path: "/menuManager",
        element: <MenuManager />,
        handle: { title: "模块设置" },
      },
      {
        path: "/operationLog",
        element: <OperationLog />,
        handle: { title: "操作日志" },
      },
      // 使用动态路由组件处理所有其他路径
      {
        path: "*",
        element: <DynamicRoute />,
        handle: { title: "动态页面" },
      },
    ],
  },
  {
    path: "/login",
    element: <Login />,
  },
];

// 创建路由配置
const createAppRoutes = () => {
  return baseRoutes;
};

export default createAppRoutes;
